package com.kedacom.general.controller;

import com.alibaba.fastjson.JSONObject;
import com.kedacom.general.result.ResponseMessage;
import com.kedacom.general.service.RequestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Slf4j
@RestController
public class RequestController {
    @Autowired
    private RequestService requestService;
    @RequestMapping("/**")
    public ResponseMessage test(HttpServletRequest request, HttpServletResponse response){
        log.info("********************************开始");
        ResponseMessage responseMessage = requestService.sendService(request);
        if (request.getRequestURI().contains("get/baseString") || request.getRequestURI().contains("login_page/queryPic") || request.getRequestURI().contains("download")){
            JSONObject result = (JSONObject) responseMessage.getResult();
            if(result!=null){
                String base64 = result.getString("baseCode");
                getImageByBase64(base64,response);
            }
        }
        log.info("********************************结束");
        return responseMessage;
    }
    private void getImageByBase64(String base64, HttpServletResponse response) {
        org.apache.commons.codec.binary.Base64 base = new org.apache.commons.codec.binary.Base64();
        byte[] decode = base.decodeBase64(base64.getBytes());
//        byte[] decode = Base64.getMimeDecoder().decode(base64);
        ByteArrayOutputStream output=new ByteArrayOutputStream();
        try {
            output.write(decode);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            ServletOutputStream out=response.getOutputStream();
            output.writeTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
